#!/usr/bin/env python2.5
# -*- coding: UTF-8 -*- 

 
from nmpacks.milonpy import NMutl 
from nmpacks.milonpy  import NMserver
#run_wsgi_app = NMserver.run_wsgi_app
db=NMserver.db 
re=db.re
 
from google.appengine.api import users
#from google.appengine.ext.webapp import template 
run_wsgi_app =NMserver.webapp.util.run_wsgi_app
# NMserver.NMserverrun_wsgi_app


from django import newforms as forms
#from appengine_django.models import BaseModel
#from google.appengine.ext.db.djangoforms import BaseModel

from google.appengine.ext.db import djangoforms
 
import models
country_list=models.country_list
 
#from nmpacks.milonpy import NMutl as utl
from nmpacks.milonpy import NMre as NMre
html=NMserver.html 
import geo  

class country_listForm(djangoforms.ModelForm): 
    # for a multichoise tag selection => http://pandemoniumillusion.wordpress.com/2008/08/20/better-way-to-use-djangos-selectmultiple-in-google-app-engine-for-a-listproperty/
    defaultSize=90
    defaltMaxlength=120
    key_name= forms.CharField(widget=forms.TextInput(attrs={'size':defaultSize, 'maxlength':defaltMaxlength}),  required=False )
    title   = forms.CharField(widget=forms.TextInput(attrs={'size':defaultSize, 'maxlength':defaltMaxlength}), help_text='120 characters max.' )
    lng     = forms.CharField(widget=forms.TextInput(attrs={'size':4,'maxlength':2 }) ) 
    #url     = forms.CharField(widget=forms.TextInput(attrs={'size':defaultSize, 'class':'nm-blue'}) ) 
    req_path= forms.CharField(widget=forms.TextInput(attrs={'size':defaultSize}) ) 
    # RadioSelect SelectMultiple db.Query(MyModel)
    #tags = forms.CharField(widget=forms.RadioSelect(attrs={'size':10,'choises':['a', 'b', 'c'] }) )
    #choisedic={'fff':'AAA', 'yyy':'BBB'}
  
    #tags = forms.CharField(widget=forms.CheckboxSelectMultiple(choises=choisedic ) )
#    tags =  forms.CharField(
#                        widget=forms.CheckboxSelectMultiple(),
#                        choices=  choisedic     #[(m.key(), m.name) for m in choisedic]
#                     )
    StatisticsDictCashe=geo.getStatisticsDictCashe() 
    tagChoises=StatisticsDictCashe.get('tagGroups', [])  
    tagChoises=[ (tag,  tag)  for tag in tagChoises ]    
    #tagChoises = ( ('tag 1', 'Economy'), ('Tag 2','Geograpy'))
    #OK Works tags = forms.MultipleChoiceField(required=False, choices=TOWN_CHOICES, widget=forms.CheckboxSelectMultiple)
    tags = forms.MultipleChoiceField(required=False, choices=tagChoises , widget=forms.CheckboxSelectMultiple)
    descr   = forms.CharField(widget=forms.Textarea(attrs={
        'id':'nm-description',
        'rows': 4,
        'cols': defaultSize})) 
    # OK tags = forms.MultipleChoiceField(required=False, choices=TOWN_CHOICES, widget=forms.CheckboxSelectMultiple)    
    #tags = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 20}))    
    class Meta:
        model = country_list
        exclude = ['hits', 'rating', 'user']
        #max_length=100

def StdMenu(lng): 
    tmp= html.ul( html.a('Home','', '/geo/'+lng+'/home.html' )  ,  'class=\"nm-hnav\"' ) 
    tmp.insertContents(  html.ul.li('&nbsp', 'class=\"nm-hnav-sep\"') )
    tmp.attrSetClass('nm-hnav') 
    return tmp
 
  
def DBmenu():
    return """
    <li>
        <a href="/geo/en/statistics/Home/Miscelaneus.html">Miscelaneus</a>  
        <li><a href="#">Country List</a> 
        <ul> 
            <li><a href="/adminops/en/db/country_list/add//">add</a> </li>  
            <li><a href="/adminops/en/db/country_list/del//">delete all</a> </li>  
        </ul>  
    </li>
    """ 
class DBoperationsRQH(NMserver.ReqHadlerNM): 
    cookieName_Path=[] 
    useCashe = 0
    isStaticContent=False 
    tmplHeader = """<p id="nm_beta"  class ="nm-inline">  * βeta </p> """   
    tmplHead="""
        <title>DB Operations</title> 
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" > 
        <meta name="robots" content="noindex,nofollow" >       
        <link rel="stylesheet" href="http://yui.yahooapis.com/2.7.0/build/reset-fonts-grids/reset-fonts-grids.css" type="text/css">
        <link rel="stylesheet" href="/media/css/yuinm.css" type="text/css" media="screen, projection">   
        <link rel="stylesheet" href="/media/css/nmforms.css" type="text/css" media="screen, projection">   
         """
    tmplFooter="""<div class="nm-cnt01"> &nbsp </div> <div class="nm-cnt02"> &nbsp </div> <div  class="nm-cnt03"> &nbsp </div>"""
    def postC(self,lng, arg_model, arg_operation, arg): 
#        import sys
#        print sys.path
#        return
#        
#        crazy = models.AppValues(title='Crazy like a diamond',
#             author='Lucy Sky',
#             publish_date='yesterday',
#             rating=5.0)   
#        crazy.put()   
#        print 'ok ' * 10 
#        return
        if arg_model=='country_list': 
            self.request.POST['tags']=self.request.POST.getall('tags' )
            
            if self.request.POST['key_name']==u"":self.request.POST['key_name']=NMre.reSlugify(self.request.POST['title'])
            data = country_listForm(data=self.request.POST) 
        else:
            return
        #data = country_listForm(data=self.request.POST)
        if data.is_valid(): 
            entity = data.save(commit=False) 
            entity.put()
            #self.response.out.write(entity.to_xml()) 
            self.redirect(self.request.environ ['PATH_INFO'])
        else:  
            return self.get_postDisplay(lng, arg_model, arg_operation, arg, data) 
            #self.response.out.write (self.get_postDisplay(lng, arg_model, arg_operation, arg, data)   )
            #self.get(lng, arg_model, arg_operation, arg) 
            
    def getC(self,lng, arg_model, arg_operation, arg): 
        return  self.get_postDisplay(lng, arg_model, arg_operation, arg) 
        
    def get_postDisplay(self,  lng, arg_model, arg_operation, arg, ModelForm=None):
        ytml=html.y_html(html.y_html.width.doc3,   sbar=html.y_html.sidebar.t3)    
        #site = ' geognos.com ' 
        ##self.tmplD={'description': site + arg + ' page','inclmap':False,'title':site + arg, 'keywords':'', 'lang':'', 'frmAction': "/geo/switch/", 'frm2Action':"/geo/switch/" , 'frmOptions':''}        
        ytml.setdefaults('DB Operations',  self.tmplFooter , html.p(''), False,  'nm-operations')     
        ytml.cntr_panel.insertContents(html.incl(self.tmplHeader)) 
        ytml.html_head.insertContents(html.incl (self.tmplHead))    
        mnuConts = StdMenu('en')
        mnuConts.insertContents(DBmenu())
        ytml.mnuConts.insertContents(mnuConts) 
        nm_sidebar_l1_cont = html.rowCont ("FOO", html.div() , "nm_sidebar_l1_cont", 2) 
        
        nm_divRowcontents= html.div(html.incl(''), 'id=\"nm_divrowcontents"')
        tmpCont=html.div(html.h2(arg_operation))
        model=eval(arg_model)
        if ModelForm is None:
            if arg_model=='country_list':ModelForm= country_listForm() 
        if arg_operation=='add': tmpCont=renderForm(ModelForm, self.request.environ ['PATH_INFO'], {'lng':'en'} ) 
        elif arg_operation=='del': 
            model.delete()
        nm_divRow=html.rowCont("%s : %s" %(arg_model, arg_operation) , nm_divRowcontents , False, 2)  
        contents=html.rowCont(tmpCont, nm_divRowcontents , False, 3)  
        nm_divRow.insertContents(contents) 
        
        ytml.doc_bd_cnts.insertContents(nm_divRow) 
        ytml.doc_bd_sidebar.insertContents(html.div(nm_sidebar_l1_cont,'id=\"nm_sidebar_l1\" class=\"nm-lev-02\"' ))    
        return ytml()
 
def renderForm(frm, action, initialValsDict=None):
    #initialValsDict={'lng':'en'}   
    if not initialValsDict is None :frm.initial=initialValsDict
    modelName= NMutl.class_typeStrNoSuper(str(frm.Meta().model))
    #print str(dir(frm.Meta()) ) 
    #print str(dir(frm) )
    tmp=html.table(footerlst=['&rArr;',  html.input('', 'class=\"nm-button"',  type='submit')],  contentsStr=unicode(frm))
    tmp.attrSetClass('nm-tbl-dj') 
    tmp=html.form(tmp, method='post', action=action)
    tmp.attrSetClass("%s %s%s" %('nm-frm-dj','nm-model-', modelName) )
    #tmp.attrAppendClass('nm-model'+modelName)
    #contents='', attributes='',  method="get", action=False):
    #contentslst = [], attributes='',caption = False, headerlst = [], footerlst= [], 
    #contents='', attributes='',  value=False, type='button'):
    
    return tmp()
class MainPage(NMserver.webapp.RequestHandler):
    def get(self):
        self.response.out.write('<html><body>'
                                '<form method="POST" '
                                'action="/test/">'
                                '<table>') 
        self.response.out.write(country_listForm())
        self.response.out.write('</table>'
                                '<input type="submit">'
                                '</form></body></html>')
                                
    def post(self):
        data = country_listForm(data=self.request.POST)
        
        if data.is_valid():
            # Save the data, and redirect to the view page
            entity = data.save(commit=False)
            entity.added_by = users.get_current_user()
            entity.put()
            self.redirect('/test/items.html')
        else:
            # Reprint the form
            self.response.out.write('<html><body>'
                                    '<form method="POST" '
                                    'action="/test/">'
                                    '<table>')
            self.response.out.write(data)
            self.response.out.write('</table>'
                                    '<input type="submit">'
                                    '</form></body></html>')
                                    
class ItemPage(NMserver.webapp.RequestHandler):
    def get(self):
        query = db.GqlQuery("SELECT * FROM country_list") # ORDER BY hits")
        for item in query:
            self.response.out.write("%s %s %s tag0 : %s<br>" %
                                    (item.url, item.tags, item.title, item.tags[0]))

def main():
    
    application = NMserver.webapp.WSGIApplication(
                                         [
                                          #(r"/geo/(?P<lang>.*?)/cc/(?P<country>.*)\.html", MainPageRQH), 
                                          (r"/adminops/(?P<lng>.*?)/db/(?P<arg_model>.*)/(?P<arg_operation>.*)/(?P<arg>.*)/", DBoperationsRQH), 
                                          #(r"/adminops/(?P<lang>.*?)/(?P<opertype>.*)/(?P<arg1>.*)/(?P<arg2>.*)/(?P<arg3>.*)/.*", MainPageRQH), 
                                     #  (r"/adminops/(?P<lang>.*?)/(?P<opertype>.*)\(?P<arg1>.*)\(?P<arg2>.*)\(?P<arg3>.*)", MainPageRQH), 
                                          ('/test/', DBoperationsRQH),
                                          ('/test/items.html', DBoperationsRQH) 
                                          ],
                                         debug=True)
    run_wsgi_app(application)

if __name__=="__main__":
    main()
